import axios from 'axios';
import cancelFetch from './cancelFetch';
// import store from '@/store/index';
// import router from '@/router/index';
import utils from '@/utils/index';

import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';

const fetch = axios.create({
  // baseURL: process.env.BASE_API, // api 的 base_url
  // baseURL: '/develop',
  // timeout: 500 // 请求超时时间
  timeout: 60000 * 2, // 请求超时时间
});

let timeFn = null;
let loading = null;
fetch.interceptors.request.use(
  (config) => {
    if (config.withLoading) {
      loading = ElLoading.service();
    }

    // cancelFetch.removePending(config);
    // cancelFetch.addPending(config);

    // 让每个请求携带自定义token
    // let userInfo = utils.getlocalStorage('userInfo') || {};
    // config.headers['Authorization'] = 'Bearer ' + userInfo.sessionId;

    // if (config.url.indexOf('logout') > -1) {
    //     config.headers['Authorization'] = ''
    // }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

fetch.interceptors.response.use(
  ({ status, data, config }) => {
    if (status === 200 || status === 201) {
      if (data.code === 0) {
        if (config.withLoading) {
          setTimeout(() => {
            loading.close();
          }, 200);
        }
        return Promise.resolve(data);
      }
    }
    // debugger
    let message = data.message || '响应失败';
    ElMessage.warning({
      type: 'warning',
      message: message,
    });

    return Promise.reject(data);
  },
  (error) => {
    console.log(error);
    if (error && error.config && error.config.withLoading) {
      setTimeout(() => {
        loading.close();
      }, 200);
    }

    if (error && error.response && error.response.status === 401) {
      // 执行退出逻辑
      clearTimeout(timeFn);
      timeFn = setTimeout(() => {
        ElMessage.error('身份过期，请重新登录');
        // store.dispatch('clearSession');
      }, 500);
    } else {
      ElMessage.error('网络连接错误，请稍后再试');
    }
    return Promise.reject(error);
  },
);

export default fetch;
